package com.cgtong.android.mvp.presenter;

import android.content.ContentValues;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.bean.UserInfoBean;
import com.cgtong.android.db.UserAccount;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.LoginContract;
import com.cgtong.android.mvp.model.LoginModel;
import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import com.zhouyou.http.subsciber.IProgressDialog;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.Date;

/**
 * Created by Sky.Bing on 2017/10/23.
 */

public class LoginPresenter implements LoginContract.Presenter {
    private LoginContract.View mView;
    private LoginModel mLoginModel;

    public LoginPresenter(LoginContract.View view) {
        this.mView = view;
        mLoginModel = new LoginModel();
    }

    @Override
    public void sendValidCode(String phone) {
        mLoginModel.sendValidCode(phone, new SimpleCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                mView.breakClickValidCode();
            }

            @Override
            public void onError(ApiException e) {
                mView.sendValidCodeError(e);
            }
        });
    }

    @Override
    public void doLogin(String phone, String password,String mobileInfo, IProgressDialog dialog) {
        doLogin(phone, password,mobileInfo, "", dialog);
    }

    @Override
    public void doLogin(String phone, final String password,String mobileInfo, String validCode, IProgressDialog dialog) {
        mLoginModel.doLoginByDialog(phone, password, mobileInfo,validCode, dialog, new SimpleCallBack<String>() {
            @Override
            public void onError(ApiException e) {
                if (e.getCode() == ConstantManager.ACCESS_TOKEN_EXPIRED
                        || e.getCode() == ConstantManager.ACCESS_USER_FORBIDDEN) {
                    return;
                }
                mView.onLoginError(e);
            }

            @Override
            public void onSuccess(String s) {
                try {
                    JSONObject jsonObj = new JSONObject(s);
                    int code = jsonObj.getInt("code");
                    if (code == ConstantManager.ACCESS_TOKEN_EXPIRED
                            || code == ConstantManager.ACCESS_USER_FORBIDDEN) {
                        return;
                    }
                    if (jsonObj.get("data") instanceof JSONObject) {
                        UserInfoBean userInfoBean = new Gson().fromJson(s, UserInfoBean.class);
                        if (userInfoBean.getCode() == 0) {
                            if (DataSupport.findFirst(UserAccount.class) != null) {
                                ContentValues values = new ContentValues();
                                values.put("loginStatus", ConstantManager.LOGIN_OUT);
                                DataSupport.updateAll(UserAccount.class, values);
                            }
                            UserInfoBean.UserInfoBeanObj userInfo = userInfoBean.getData();
                            UserAccount userAccount = new UserAccount(userInfo);
                            userAccount.setToken(userInfoBean.getMsg());
                            userAccount.setPassword(password);
                            HttpParams params = new HttpParams();
                            params.put("accessToken", userAccount.getToken());
                            params.put("platform", ConstantManager.PLATFORM);
                            EasyHttp.getInstance().addCommonParams(params);
                            userAccount.setLoginStatus(ConstantManager.LOGIN_IN);
                            userAccount.setLoginTime(TimeUtils.date2String(new Date()));
                            UserAccount userFromDb = App.getInstance().findAccountByUserId(String.valueOf(userAccount.getUserId()));
                            if (null != userFromDb) { //exists
                                //将redEnvelopes设置成默认值，litepal框架设计如此
                                if(userAccount.getRedEnvelopes() == 0){
                                    userAccount.setToDefault("redEnvelopes");
                                }
                                userAccount.setId(userFromDb.getId());
                                userAccount.update(userFromDb.getId());
                                mView.backActivity(userAccount.getToken());
                            } else {
                                if (userAccount.save()) {
                                    mView.backActivity(userAccount.getToken());
                                }
                            }
                        } else {
                            ToastUtils.showLong(userInfoBean.getMsg());
                        }
                    } else {
                        //ToastUtils.showLong(jsonObj.getString("msg"));
                        mView.onLoginError(new ApiException(new Exception(jsonObj.getString("msg")), jsonObj.getInt("code")));
                    }
                } catch (Exception e) {
                    ToastUtils.showLong(R.string.txt_error_login);
                }
            }
        });
    }
}